﻿using System;
using System.Collections.Generic;
using System.Linq;
using Model.Entity;
using Ones.Dal.Infrastructure;
using Ones.Dal.Repository.Interfaces;

namespace Ones.Dal.Repository.Impl
{
    public class DivisionDao : AbstractDao<Division>, IDivisionDao
    {
        public override bool
        create(Division div)
        {
            try
            {
                div.divId = this.createPrefixId();

                _ctx.Divisions.InsertOnSubmit(div);
                _ctx.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public override bool
        update(Division div)
        {
            try
            {
                var curr = getById(div.divId);

                curr.divName = div.divName;
                curr.divDescription = div.divDescription;

                _ctx.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public string
        createPrefixId()
        {
            string currMaxId = getAll().Max(i => i.divId);
            string prefixPart = "div";
            int nDigits = 3;

            AutoId autoid = new AutoId();

            return autoid.tryCreatePrefixId(currMaxId, prefixPart, nDigits);
        }

        public override Division
        getById(object id)
        {
            return getSingle(i => i.divId.Equals((string)id));
        }

        public List<Division>
        getByName(string divName)
        {
            try
            {
                return getMultiple(i => i.divName.Contains(divName)).ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public Division
        getByNameExactly(string divName)
        {
            return getSingle(i => i.divName.Equals(divName));
        }
    }

    #region IDivisionDao

    public interface IDivisionDao : IDao<Division>
    {
        String createPrefixId();

        List<Division> getByName(String divName);

        Division getByNameExactly(String divName);
    }
    #endregion
}